import 'package:flutter/material.dart';
import 'package:novel_reader/model/book.dart';
import 'package:novel_reader/model/chapter.dart';
import 'package:novel_reader/utils/back_handler.dart';
import 'package:novel_reader/utils/hive_storage.dart';
import 'package:novel_reader/utils/reader_operation.dart';
import 'package:novel_reader/widgets/book_chapter_selector.dart';

class Home extends StatefulWidget {
  const Home({super.key});

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  List<Book> _books = [];
  String? _showTitle;
  String? _showContent;
  double _horizontalDragDistance = 0;
  BackHandler? _backHandler;
  ReaderOperation? _readerOperation;
  final ScrollController _scrollController = ScrollController();
  final GlobalKey<BookChapterSelectorState> _bcSelectorKey =
      GlobalKey<BookChapterSelectorState>();

  @override
  void initState() {
    super.initState();
    _backHandler = BackHandler(this);
    _readerOperation = ReaderOperation(this);
    checkStatusAndLoad();
  }

  checkStatusAndLoad() {
    if (!HiveStorage.isReady()) {
      Future.delayed(Duration(seconds: 1), () => checkStatusAndLoad());
      return;
    }
    _readerOperation?.loadingTask(() {
      List<Book>? books = HiveStorage.getAllBooks();
      if (books.isEmpty) {
        _readerOperation?.addBook(books, 'n5864cn', () {
          setState(() {
            _books = books;
          });
        });
      } else {
        setState(() {
          _books = books;
        });
      }
    });
  }

  void onChapterSelected(
    Book book,
    List<Chapter> chapters,
    Chapter chapter,
    bool refresh,
  ) {
    _readerOperation?.loadingTask(() async {
      String? s = await chapter.getTranslation(
        refresh,
        () => HiveStorage.saveChapter(chapter),
      );
      _scrollController.jumpTo(0);
      setState(() {
        _showTitle =
            "${chapter.title} (${chapter.index}/${chapters.length}) (${chapter.update})";
        _showContent = '$_showTitle\n\n$s';
      });
      book.reading = chapters.indexOf(chapter);
      HiveStorage.saveBook(book);
    });
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (bool didPop, Object? result) =>
          _backHandler?.handleBackPressed(didPop),
      child: Scaffold(
        body: SafeArea(
          child: Container(
            color: Colors.black,
            child: Column(
              children: [
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.all(6.0),
                    child: GestureDetector(
                      onHorizontalDragStart: (details) =>
                          _horizontalDragDistance = 0.0,
                      onHorizontalDragUpdate: (details) =>
                          _horizontalDragDistance += details.delta.dx,
                      onHorizontalDragEnd: (details) {
                        if (_horizontalDragDistance > 50) {
                          _bcSelectorKey.currentState?.previousChapter();
                        } else if (_horizontalDragDistance < -50) {
                          _bcSelectorKey.currentState?.nextChapter();
                        }
                      },
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        scrollDirection: Axis.vertical,
                        child: Text(
                          _showContent ?? '',
                          style: TextStyle(color: Colors.grey, fontSize: 16),
                        ),
                      ),
                    ),
                  ),
                ),
                Container(
                  padding: EdgeInsets.all(6),
                  constraints: const BoxConstraints(minWidth: double.infinity),
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(color: Colors.grey.shade700),
                    ),
                  ),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.horizontal,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ConstrainedBox(
                          constraints: const BoxConstraints(
                            minWidth: 120,
                            maxWidth: 300,
                          ),
                          child: BookChapterSelector(
                            key: _bcSelectorKey,
                            bookData: _books,
                            onChapterSelected: onChapterSelected,
                          ),
                        ),
                        SizedBox(width: 10),
                        OutlinedButton(
                          child: Text('刷新章节'),
                          onPressed: () => _bcSelectorKey.currentState
                              ?.updateChapters(_readerOperation),
                        ),
                        SizedBox(width: 10),
                        OutlinedButton(
                          child: Text('更新文章'),
                          onPressed: () => _bcSelectorKey.currentState
                              ?.updateChapter(_readerOperation),
                        ),
                        SizedBox(width: 10),
                        OutlinedButton(
                          child: Text('添加书籍'),
                          onPressed: () =>
                              _readerOperation?.showAddBook(_books),
                        ),
                        SizedBox(width: 10),
                        OutlinedButton(
                          child: Text('删除书籍'),
                          onPressed: () => _bcSelectorKey.currentState
                              ?.removeBook(_readerOperation),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
